<template>
  <div class="config-container">
      <el-row>
        <el-row class="cptTitle">
          <el-col :span="24"><div>{{configBarShow ? '组件配置':'大屏配置'}}</div></el-col>
        </el-row>
        
        <el-tabs class="my-tabs" v-show="configBarShow" v-model="configTab" :stretch="true">
          <el-tab-pane label="坐标" name="basic">
            <el-form class="my-form"  label-width="100px">
              <el-form-item label="宽度：">
                <el-input-number :min="20" :max="2000" v-model="currentCpt.cptWidth"  size="small"/>
              </el-form-item>
              <el-form-item label="宽度：">
                <el-input-number :min="20" :max="1500" v-model="currentCpt.cptHeight" size="small" />
              </el-form-item>
              <el-form-item label="X轴：">
                <el-input-number :min="-500" :max="2500" v-model="currentCpt.cptX" size="small" />
              </el-form-item>
              <el-form-item label="Y轴：">
                <el-input-number :min="-500" :max="1500" v-model="currentCpt.cptY" size="small" />
              </el-form-item>
              <el-form-item label="Z轴：">
                <el-input-number :min="1" :max="1800" v-model="currentCpt.cptZ" size="small" />
              </el-form-item>
            </el-form>
            
          </el-tab-pane>
          <el-tab-pane label="属性" name="custom">
            <div class="customForm" :style="{height:(height-140)+'px'}" v-if="currentCpt && currentCpt.cptOption">
              <component :is="currentCpt.cptOptionKey?currentCpt.cptOptionKey: + currentCpt.cptKey+'-option'" :attribute="currentCpt.cptOption.attribute" className="my-form" />
            </div>
          </el-tab-pane>
          <!--      展示数据表单需在option.js初始化cptDataForm-->
          <el-tab-pane label="数据" name="data" v-if="cptDataFormShow">
            <div class="customForm" :style="{height:(height-140)+'px'}">
              <el-form class="my-form" size="mini" label-position="top">
                <el-form-item label="数据类型">
                  <el-radio-group v-model="currentCpt.cptOption.cptDataForm.dataSource" @change="changeDataSource">
                    <el-radio :label="1">静态数据</el-radio>
                    <el-radio :label="2">接口</el-radio>
                    <!-- <el-radio :label="3">sql</el-radio> -->
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="轮询" v-show="currentCpt.cptOption.cptDataForm.dataSource !== 1">
                  <el-switch v-model="dataPollEnable" active-text="开启" inactive-text="关闭"/>
                </el-form-item>
                <el-form-item label="轮询时间(s)" v-show="dataPollEnable">
                  <el-input-number v-model="currentCpt.cptOption.cptDataForm.pollTime" :min="0" :max="100" label="描述文字"/>
                </el-form-item>
                <!-- 解析接口参数 -->
                <el-form-item label="接口参数" v-show="currentCpt.cptOption.cptDataForm.dataSource === 2">
                  <ApiParams ref="apiParams" :query="currentCpt.cptOption.cptDataForm.passParams" @saveParams="saveParams"/>
                </el-form-item>
                <el-form-item :label="dataLabels[currentCpt.cptOption.cptDataForm.dataSource - 1]">
                  <el-input v-show="currentCpt.cptOption.cptDataForm.dataSource === 2"
                      type="textarea" :rows="5" v-model="currentCpt.cptOption.cptDataForm.apiUrl"/>
                  <vue-json-editor
                    v-show="currentCpt.cptOption.cptDataForm.dataSource === 1"
                    v-model="dataJson" 
                    class="my-json-editor"
                    :show-btns="false" 
                    :expandedOnStart="true" 
                    mode="code"
                  />
                   
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" style="width: 100%" @click="refreshCptData">{{ currentCpt.cptOption.cptDataForm.dataSource === 2 ? '请求接口' : '刷新数据' }}</el-button>
                </el-form-item>
              </el-form>
              <codemirror 
                class="code"
                ref="myCodemirror" 
                v-show="currentCpt.cptOption.cptDataForm.dataSource === 2"
                v-model="resPreview" 
                :options="cmOptions" 
              />
              <!-- 默认将返回的全部数据作为组件的数据源， 开启筛选字段-->
              <div v-if="currentCpt.cptOption.cptDataForm.dataSource === 2 && paramList.length">
                <div style="font-size:14px; color:#606266; margin-right:4px">筛选字段</div>
                <div style="margin:6px 0; display:flex; align-items:center; white-space:nowrap; ">
                  <el-select class="my-select" style="flex:1" v-model="currentCpt.cptOption.cptDataForm.paramKey" placeholder="选择要应用的字段">
                    <el-option v-if="isChart" :key="'all'" :label="'全部'" :value="'all'"></el-option>
                    <el-option v-for="item in paramList"
                        :key="item" :label="item" :value="item">
                    </el-option>
                  </el-select>
                  <el-select class="my-select" style="flex:1" v-show="valueKeyList.length" v-model="currentCpt.cptOption.cptDataForm.valueKey" placeholder="选择要应用的二级字段">
                    <el-option v-for="item in valueKeyList"
                        :key="item" :label="item" :value="item">
                    </el-option>
                  </el-select>
                </div>
                <el-button type="primary" size='mini' style="width:100%;" @click="updateCptData" >应用字段</el-button>
              </div>
              
              
            </div>
          </el-tab-pane>
        </el-tabs>
        <div v-show="!configBarShow" style="margin-top: 10px;">
          <el-form class="my-form" :model="designData" label-width="100px" size="small">
            <el-form-item label="网站标题">
              <el-input v-model="designData.title" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="网站描述">
              <el-input type="textarea" v-model="designData.simpleDesc"></el-input>
            </el-form-item>
            <el-form-item label="分辨率X">
              <el-input-number v-model="designData.scaleX" :min="640" :max="10240" style="width: 100%"/>
            </el-form-item>
            <el-form-item label="分辨率Y">
              <el-input-number v-model="designData.scaleY" :min="320" :max="10240" style="width: 100%"/>
            </el-form-item>
            <el-form-item label="背景颜色">
              <el-color-picker v-model="designData.bgColor" show-alpha/>
            </el-form-item>
            <el-form-item label="背景图片">
              <div v-if="designData.bgImg" style="width: 100%;height: 100%;position: relative">
                <img :src="getFullFilePath(designData.bgImg)" style="width: 100%;height: 100%;"/>
                <i style="position: absolute;z-index: 6;right: 0;font-size: 20px;color: #FFCCCC"
                   class="el-icon-delete" @click.stop="handleRemove"></i>
              </div>
              <div v-else class="uploadItem" @click="showGallery">
                <i style="font-size: 40px;color: #aaa" class="el-icon-plus"></i>
              </div>
            </el-form-item>
            <el-form-item label="个性链接">
              <el-input disabled v-model="designData.id" autocomplete="off"/>
            </el-form-item>
            <el-form-item label="访问码">
              <el-input v-model="designData.viewCode" autocomplete="off"/>
            </el-form-item>
          </el-form>
        </div>
      </el-row>
      <gallery ref="gallery" @confirmCheck="confirmCheck"/>
  </div>
</template>
<script>
import { isJSON } from '@/utils/myutils';
import { getFile } from '@/api/ImgPool';
import vueJsonEditor from 'vue-json-editor';
import { codemirror } from 'vue-codemirror';
import 'codemirror/addon/display/autorefresh'
import 'codemirror/lib/codemirror.css';
import 'codemirror/keymap/sublime'; //sublime编辑器效果
import 'codemirror/theme/dracula.css'; // 配置里面也需要theme设置为monokai
import 'codemirror/mode/sql/sql.js'; // 配置里面也需要mode设置为vue
import 'codemirror/addon/selection/active-line';
import {fileUrl} from "/env";
import Gallery from "@/components/gallery"; //光标行背景高亮，配置里面也需要styleActiveLine设置为true
import ApiParams from './ApiParams';
export default {
  name: 'configBar',
  props: {
    currentCpt: Object,
    designData: Object,
    height:Number,
    apiDataStores:Object
  },
  components: {
    Gallery,
    vueJsonEditor,
    codemirror,
    ApiParams
  },
  watch: {
    currentCpt(newVal) {
      // staticCurrentCpt = newVal;
      this.cptDataFormShow = false;
      if (!newVal || !newVal.cptOption) {
        this.configBarShow = false;//清空时
      } else {
        if (this.currentCpt.cptOption.cptDataForm) {
          this.cptDataFormShow = true;
        } else {
          this.configTab = 'basic'; //解決上一組件沒有数据表单导致tab栏未选中bug
        }
      }
    },
    updating(newValue){
        console.log('watcher...', newValue);
        // console.log(staticCurrentCpt);
        if ( !this.currentCpt.cptKey ) return;
        let apiStr = this.currentCpt.id;
        if ( this.apiDataStores[apiStr] ) {
          // json格式化
          this.resPreview = JSON.stringify(this.apiDataStores[apiStr], null, "\t");
          let keys = Object.keys(this.apiDataStores[apiStr]);
          // 判断第一级字段(图表数据源做特殊处理)
          // console.log(keys);
          if ( this.isChart ) {
            if ( keys.length ) {
                  let item = this.apiDataStores[apiStr][keys[0]];
                  if ( item && typeof item === 'object' ) {
                      this.paramList = Object.keys(item);
                  }
              }
          } else {  
            this.paramList = keys;
          }
        } else {
          this.resPreview = '接口没有返回任何数据，请检查接口!';
          this.paramList = [];
        }
    }    
  },
  computed: {
    updating(){
      return this.apiDataStores;
    },
    isChart(){
      return this.currentCpt.cptKey === 'cpt-chart-column' || this.currentCpt.cptKey === 'cpt-chart-line' || this.currentCpt.cptKey === 'cpt-chart-pie' ? true : false;
    },
    dataPollEnable: {
      get() {
        return !!(
          this.currentCpt.cptOption.cptDataForm &&
          this.currentCpt.cptOption.cptDataForm.pollTime &&
          this.currentCpt.cptOption.cptDataForm.pollTime !== 0
        );
      },
      set(newValue) {
        if (newValue) {
          this.currentCpt.cptOption.cptDataForm.pollTime = 8;
        } else {
          this.currentCpt.cptOption.cptDataForm.pollTime = 0;
          this.refreshCptData(); //清除定时器
        }
        return newValue;
      },
    },
    valueKeyList(){
      let apiStr = this.currentCpt.id;
      if ( this.apiDataStores[apiStr] ) {
        if ( this.isChart ) {
          return [];
        }
        if ( this.currentCpt.cptOption.cptDataForm.paramKey ) {
          let paramValue = this.apiDataStores[apiStr][this.currentCpt.cptOption.cptDataForm.paramKey];
          // 如果根据paramKey取到的字段值是对象，则进一步筛选字段
          if ( typeof paramValue === 'object' ) {
            return Object.keys(paramValue);
          }
        }
      }
      return [];
    },
    dataJson: {
      get() {
        if (isJSON(this.currentCpt.cptOption.cptDataForm.dataText)) {
          return JSON.parse(this.currentCpt.cptOption.cptDataForm.dataText);
        } else {
          return {};
        }
      },
      set(newValue) {
        this.currentCpt.cptOption.cptDataForm.dataText = JSON.stringify(newValue);
      },
    },
  },
  data() {
    return {
      fileUrl:fileUrl,
      cptDataFormShow: false,
      configTab: 'custom',
      dataLabels: ['数据', '接口地址', 'sql'],
      configBarShow: false,
      hasJsonFlag: true,
      // api接口参数字段
      passParamList:[],
      // api返回数据
      resPreview:'接口没有返回任何数据，请检查接口!',
      paramList:[],
      cmOptions: {
        autoRefresh:true, // 自动刷新，解决初始化不显示
        tabSize: 4, // tab的空格个数
        theme: 'dracula', //主题样式
        lineNumbers: true, //是否显示行数
        lineWrapping: true, //是否自动换行
        styleActiveLine: true, //line选择是是否加亮
        matchBrackets: true, //括号匹配
        mode: 'text/x-sparksql', //实现javascript代码高亮
        readOnly:true, //只读

        keyMap: 'default',
        extraKeys: { tab: 'autocomplete' },
        foldGutter: true,
        gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
        hintOptions: {
          completeSingle: false,
          tables: {},
        },
      },
    };
  },
  methods: {
    confirmCheck(fileUrl){
      this.designData.bgImg = fileUrl;
    },
    showGallery(){
      this.$refs.gallery.opened();
    },
    handleRemove(){
      this.designData.bgImg = ''
    },
    changeDataSource(val) {
      //静态数据不显示轮询按钮
      if (val === 1) {
        this.currentCpt.cptOption.cptDataForm.pollTime = 0;
      }
    },
    // 刷新数据，调用父组件(index)中refreshCptData方法
    // 在父组件中再调用选中图层中的refreshCptData方法
    // 图层中的refreshCptData方法再自行调后端接口渲染数据，文本框的内容和数据类型组装在option.cptDataForm中
    refreshCptData() {
      this.$refs.apiParams.updateParams();
      this.$emit('refreshCptData');
    },
    // 不请求接口，根据api缓存数据更新字段
    updateCptData(){
      this.$emit('updateCptData');
    },
    // 更新接口参数的键值对,保存在组件的配置中
    saveParams(arr){
      if ( arr.length ) {
        let str = arr.reduce((sum, cur)=>{ sum+=`${cur.label}=${cur.value}&`; return sum }, '');
        str = str.substring(0, str.length-1);
        this.currentCpt.cptOption.cptDataForm.passParams = str ;
      }
    },
    getFullFilePath(str){
      return getFile(str); 
    },
    showCptConfig() {
      this.configBarShow = true;
    },
  }
};
</script>

<style>
.config-container {
  width: 100%;
  height:100%;
  background:#27292d;
  overflow: hidden;
  border:1px solid #0e0f10;
  border-bottom:none;
}
.cptTitle {
  line-height: 35px;
  text-align: center;
  background:#383b41;
  color: #fff;
  border-bottom:1px solid #0e0f10;
}
.closeItem:hover {cursor: pointer;background: #2b3340;}
.customForm {padding: 0 6px 0 4px;overflow-y: scroll}
/* el-tabs 选项卡自定义组件 */
.el-tabs.my-tabs .el-tabs__nav-wrap::after {
  background:#59616d;
  height:1px;
}
.el-tabs.my-tabs .el-tabs__nav {
  background:#313336;
}
.el-tabs.my-tabs .el-tabs__nav .el-tabs__item {
  color:#fff;
}
/* el-form自定义表单样式 */
.el-form.my-form {
  color:#fff;
  font-size:1rem;
}
.el-form.my-form .el-form-item {
  margin-bottom:1rem;
}
.el-form.my-form .el-form-item .el-form-item__label {
  color:rgba(255, 255, 255, 0.85);
}
.el-form.my-form .el-form-item .el-input__inner {
  background:#33373d;
  border:1px solid #0e0f10;
  color:#fff;
}
.el-form.my-form .el-form-item .el-radio-group .el-radio {
  color:#fff;
}
.el-form.my-form .el-form-item .el-textarea__inner {
  background:#33373d;
  border:1px solid #0e0f10;
  color:#fff;
}
.el-form.my-form .el-form-item .el-input-number {
  border-radius:4px;
}
.el-form.my-form .el-form-item .el-input-number .el-input-number__decrease, .el-form.my-form .el-form-item .el-input-number .el-input-number__increase {
  border-color:#0e0f10;
  background-color:rgba(255, 255, 255, 0.15);
  color:#fff;
}
.el-form.my-form .el-form-item .el-color-picker__trigger {
  border:1px solid #0e0f10;
  padding:0;
}
.el-form.my-form .el-form-item .uploadItem {
  width: 120px;
  height: 120px;
  text-align: center;
  line-height: 120px;
  background:#33373d;
  border:1px solid #0e0f10;
  cursor: pointer
}
.el-form.my-form .el-form-item .el-switch .el-switch__label {
  color:#fff;
}
.el-form.my-form .el-form-item .el-switch .el-switch__core {
  background:#33373d;
  border:1px solid #0e0f10;
}
.el-form.my-form .el-form-item .el-switch.is-checked .el-switch__core {
  background:#409EFF;
}
.el-form.my-form .el-form-item .el-slider .el-slider__runway {
  background:#33373d;
}
/* 自定义Select组件样式 */
.el-select.my-select .el-input__inner {
  background:#33373d;
  border:1px solid #0e0f10;
  color:#fff;
}
/* JSON-editor组件样式 */
.my-json-editor .jsoneditor {
  border:1px solid #333333;
}
.my-json-editor .jsoneditor .jsoneditor-menu {
  background:#313336;
  border-bottom:none;
}
/* .my-json-editor .jsoneditor .ace-jsoneditor .ace-scroller {
  background:
} */
</style>
